package handler

import (
	"hmsDemo/hms.service/config"

	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/server"

	//"hms/hms.service/taskflow"
	"strings"
	//"hms/hms.service/config"
	"sync"
)

// 管理和 serive handler的 注册事宜

var (
	//HandlerCenter
	once  sync.Once
	defHC *HandlerCenter = nil
)

//handler 插件初始化函数
type FuncHandlerPluginInit func(*HandlerCenter) error

func GetHandlerCenter() *HandlerCenter {
	once.Do(func() {
		defHC = newHandlerCenter()
	})
	return defHC
}

//注册Web插件初始化 ,  由WebCenter执行 Web插件的初始化设置
func RegisterHandlerPlugin(pluginName string, f FuncHandlerPluginInit) {
	wh := GetHandlerCenter()
	wh.RegisterHandlerPlugin(pluginName, f)
}

type HandlerCenter struct {
	mapPlugin map[string]FuncHandlerPluginInit
	//params map[string] string
	cfg *config.ServiceConfig
	//tf      *taskflow.TaskFactory
	service micro.Service
}

func newHandlerCenter() *HandlerCenter {
	hc := new(HandlerCenter)

	hc.mapPlugin = make(map[string]FuncHandlerPluginInit)

	return hc
}

func (hc *HandlerCenter) GetParam(key string) (string, bool) {
	value, ok := hc.cfg.Params[key]
	return value, ok
}

//遍历参数,并执行操作处理函数
//函数 返回true 表示 退出循环,后续需要统一调整到config的模块中
func (hc *HandlerCenter) WalkParams(f func(key string, value string) bool) {
	for k, v := range hc.cfg.Params {
		bQuit := f(k, v)
		if bQuit {
			break
		}
	}
}

//注册handler插件
func (hc *HandlerCenter) RegisterHandlerPlugin(handlerName string, f FuncHandlerPluginInit) {
	//service全部转换为小写
	hc.mapPlugin[strings.ToLower(handlerName)] = f
}

//初始化设置, 执行各handlerPlugin的初始化函数
func (hc *HandlerCenter) Init(service micro.Service, cfg *config.ServiceConfig) {
	hc.cfg = cfg
	// hc.tf = tf
	hc.service = service
	//执行各WebPlugin的初始化设置
	for _, plugin := range hc.mapPlugin {
		plugin(hc)
	}

}

// func (hc *HandlerCenter) GetTaskFactory() *taskflow.TaskFactory {
// 	return hc.tf
// }

func (hc *HandlerCenter) GetServer() server.Server {
	return hc.service.Server()
}
